package com.example.demo3.util;

import lombok.SneakyThrows;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisLockOperate {

    long time = 3000L;

    @Resource
    protected RedisLockRegistry redisLockRegistry;

    /**
     * 尝试一次加锁，采纳默认工夫
     *
     * @param lockKey 加锁Key
     * @return java.lang.Boolean
     */
    @SneakyThrows
    public <T> Boolean tryLock(T lockKey) {
        return redisLockRegistry.obtain(lockKey).tryLock(time, TimeUnit.MILLISECONDS);
    }

    /**
     * 开释锁
     *
     * @param lockKey 解锁Key
     */
    public <T> void unlock(T lockKey) {
        redisLockRegistry.obtain(lockKey).unlock();
    }
}
